package api

import (
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/util/gconv"
	"web_api_gogf/app/model"
	"web_api_gogf/app/service"
	"web_api_gogf/library/response"
)

var SysMenu = SysMenuApi{}

type SysMenuApi struct {
}

//首页
func (s *SysMenuApi) Index(r *ghttp.Request) {
	var searchParams *model.SysMenuGetListReq
	if err := r.Parse(&searchParams); err != nil {
		response.JsonExit(r, 1, err.Error())
	}
	//菜单分组列表
	groupList, err := service.SysMenu.GetMenuGroupList()
	if err != nil {
		response.JsonExit(r, 1, err.Error())
	}
	//菜单列表
	menuList, err := service.SysMenu.GetMenuList(searchParams)
	if err != nil {
		response.JsonExit(r, 1, err.Error())
	}
	var menuTreeList []*model.SysMenusBig
	//转换为树结构数据
	if searchParams.Name == "" {
		menuTreeOriginList := ([]model.SysMenusBig)(nil)
		gconv.Structs(menuList, &menuTreeOriginList)
		menuTreeList = service.SysMenu.BuildTree(menuTreeOriginList)
	} else {
		gconv.Structs(menuList, &menuTreeList)
	}

	//权限列表
	permList, err := service.SysPermission.GetAll()
	//转换为树结构
	permTreeOriginList := ([]model.SysPermissionTree)(nil)
	gconv.Structs(permList, &permTreeOriginList)
	permTreeList := service.SysPermission.BuildTree(permTreeOriginList)
	//返回数据
	response.Json(r, 0, "加载成功", g.Map{
		"groupId":   searchParams.GroupId,
		"groupList": groupList,
		"menuList":  menuTreeList,
		"permList":  permTreeList,
	})
}

// 菜单保存
func (s *SysMenuApi) Save(r *ghttp.Request) {
	var data *model.SysMenuSaveReq
	if err := r.ParseForm(&data); err != nil {
		response.JsonExit(r, 1, err.Error())
	}
	rs, err := service.SysMenu.SaveMenu(data)
	if err != nil {
		response.JsonExit(r, 1, err.Error())
	}
	rows, err := rs.RowsAffected()
	if err != nil {
		response.JsonExit(r, 1, err.Error())
	}
	response.JsonExit(r, 0, "保存菜单成功", g.Map{
		"rows": rows,
	})
}

// 菜单删除
func (s *SysMenuApi) Destroy(r *ghttp.Request) {
	var menuIds []uint
	recMenuIds := r.Get("menu_ids")
	menuIds = gconv.SliceUint(recMenuIds)
	if menuIds == nil {
		response.JsonExit(r, 1, "请选择要删除的菜单")
	}
	rs, err := service.SysMenu.DelMenu(menuIds)
	if err != nil {
		response.JsonExit(r, 1, err.Error())
	}
	rows, err := rs.RowsAffected()
	if err != nil {
		response.JsonExit(r, 1, err.Error())
	}
	response.Json(r, 0, "删除成功", g.Map{
		"rows": rows,
	})
}
